package com.benjaminwan.read.free.ui

import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import androidx.appcompat.view.menu.MenuBuilder
import androidx.core.view.GravityCompat
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupActionBarWithNavController
import com.airbnb.mvrx.MvRx
import com.benjaminwan.read.free.R
import com.benjaminwan.read.free.base.activity.BaseActivity
import com.benjaminwan.read.free.common.REQUEST_ENABLE_BT
import com.benjaminwan.read.free.databinding.ActivityMainBinding
import com.benjaminwan.read.free.ui.main.MainFragment
import com.benjaminwan.read.free.utils.showXToastError
import com.benjaminwan.read.free.utils.showXToastInfo
import com.orhanobut.logger.Logger

class MainActivity : BaseActivity() {
    private var exitTime: Long = 0

    private val navHostFragment: NavHostFragment
        get() = supportFragmentManager.findFragmentById(R.id.fragmentContainer) as NavHostFragment

    private val navController: NavController
        get() = navHostFragment.navController

    private val mainFragment by lazy {
        MainFragment()
    }

    public lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        /*val rationaleHandler = createDialogRationale(R.string.dialog_permission_title) {
            onPermission(Permission.ACCESS_FINE_LOCATION, R.string.dialog_permission_msg)
        }

        if (!isAllGranted(Permission.ACCESS_FINE_LOCATION)) {
            askForPermissions(
                Permission.ACCESS_FINE_LOCATION,
                rationaleHandler = rationaleHandler
            ) { result ->
                val permissionGranted: Boolean =
                    result.isAllGranted(
                        Permission.ACCESS_FINE_LOCATION
                    )
                if (!permissionGranted) {
                    showXToastError(R.string.msg_permission_error)
                }
            }
        }*/
        initViews()
        getUri()
    }

    override fun onResume() {
        super.onResume()
        enableBluetoothAdapter()
    }

    private fun enableBluetoothAdapter() {
        val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
        bluetoothAdapter ?: return
        if (!bluetoothAdapter.isEnabled) {
            val enableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(
                enableIntent,
                REQUEST_ENABLE_BT
            )
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQUEST_ENABLE_BT -> {//打开蓝牙
                (resultCode == Activity.RESULT_OK).not().takeIf { it }?.apply {
                    showXToastError(R.string.msg_bluetooth_open_refuse)
                }
            }

            else -> {
            }
        }
    }

    /*override fun onResume() {
        super.onResume()
        if (!this.applicationContext.isGpsEnable()) {
            MaterialDialog.Builder(this.applicationContext)
                .title(R.string.tip)
                .content(R.string.dialog_gps_setting)
                .positiveText(R.string.dialog_goto_setting)
                .canceledOnTouchOutside(false)
                .onPositive { dialog, which ->
                    startActivityForResult(
                        Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS),
                        REQUEST_CODE_LOCATION_SOURCE_SETTINGS
                    )
                }.show()
        }
    }*/

    override fun onStart() {
        super.onStart()
        if (supportFragmentManager.findFragmentByTag(TAG) == null) {
            supportFragmentManager.beginTransaction().add(
                mainFragment,
                TAG
            ).commit()
        }
    }

    private fun initViews() {
        navController.setGraph(R.navigation.nav_graph)
        setSupportActionBar(binding.toolbar)
        setupActionBarWithNavController(navController)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        getUri()
    }

    private fun getUri() {
        val uri = intent.data
        Logger.i("uri=${uri?.toString()}")
        mainFragment.arguments = arg(intent.data)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return super.onCreateOptionsMenu(menu)
    }

    //菜单显示图标
    override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
        menu ?: return super.onPrepareOptionsMenu(menu)
        if (menu::class.java == MenuBuilder::class.java) {
            try {
                val method = menu.javaClass.getDeclaredMethod(
                    "setOptionalIconsVisible",
                    Boolean::class.java
                )
                method.isAccessible = true
                method.invoke(menu, true)
            } catch (e: Exception) {

            }
        }
        return super.onPrepareOptionsMenu(menu)
    }

    override fun onBackPressed() {
        if (binding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
            binding.drawerLayout.closeDrawers()
        } else {
            if (mainFragment.canBackPressed()) {
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    showXToastInfo(R.string.msg_press_again_to_exit_app)
                    exitTime = System.currentTimeMillis()
                } else {
                    finish()
                }
            } else {
                super.onBackPressed()
            }
        }
    }

    /*override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        Logger.i("main onKeyDown")
        if (navController.currentDestination?.id == R.id.mouseFragment) {
            val fragment = getFragment<MouseFragment>(navHostFragment) ?: return false
            return fragment.onKeyDown(keyCode, event)
        } else {
            return super.onKeyDown(keyCode, event)
        }
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        Logger.i("main onKeyUp")
        if (navController.currentDestination?.id == R.id.mouseFragment) {
            val fragment = getFragment<MouseFragment>(navHostFragment) ?: return false
            return fragment.onKeyUp(keyCode, event)
        } else {
            return super.onKeyUp(keyCode, event)
        }
    }*/

    companion object {
        const val TAG = "MainFragment"
        fun arg(uri: Uri?): Bundle {
            val args = Bundle()
            args.putParcelable(MvRx.KEY_ARG, uri)
            return args
        }
    }
}